package zpy.servlet.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import zpy.servlet.pojo.ErrorMessage;
import zpy.servlet.pojo.MyFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Servlet implementation class FileServlet
 */
@WebServlet("/FileServlet")
public class FileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String FILE_ICON_DEFAULT = " default ";//文件默认图标
	private static final String FILE_ICON_DIR   = "dir";//文件夹图标

	private static final int OPTION_QUERY          = 1; //查询
	private static final int OPTION_ADD_DIR        = 2; //添加目录
	private static final int OPTION_DELETE         = 3; //删除
	private static final int OPTION_UPLOAD_FILE    = 4; //添加目录

	private static final int PATH_TYPE_PART = 1;//相对路径
	private static final int PATH_TYPE_FULL = 2;//全路径

	//MIME类型map
	static private Map<String, String> fileIconMap;
	//图像后缀字符串
	static private String  strImgSuffix = "jpg;jpeg;png;bmp;gif";

	static{
	    	fileIconMap = new HashMap<>();
	    	fileIconMap.put("dir", "images/file_images/dir.png");
	    	fileIconMap.put("doc", "images/file_images/word.png");
	    	fileIconMap.put("docx", "images/file_images/word.png");
	    	fileIconMap.put("txt", "images/file_images/text.png");
	    	fileIconMap.put("ppt", "images/file_images/ppt.png");
	    	fileIconMap.put("pptx", "images/file_images/ppt.png");
	    	fileIconMap.put("pdf", "images/file_images/Pdf.png");
	    	fileIconMap.put("jpg", "images/file_images/jpg.png");
	    	fileIconMap.put("jpeg", "images/file_images/jpeg.png");
	    	fileIconMap.put("xls", "images/file_images/excel.png");
	    	fileIconMap.put("xlsx", "images/file_images/excel.png");
	    	fileIconMap.put("asm", "images/file_images/asm.png");
	    	fileIconMap.put("ini", "images/file_images/asm.png");
	    	fileIconMap.put("rar", "images/file_images/rar.png");
	    	fileIconMap.put("default", "images/file_images/file.png");    
	}

    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String strOption = request.getParameter("option");
		int option       = Integer.parseInt(strOption);
		switch (option) {
		case OPTION_QUERY:
		{
			queryFile(request,response);
			break;
		}
		case OPTION_ADD_DIR:
		{
			addDir(request,response);
			break;
		}
		case OPTION_DELETE:
		{
			deleteFile(request,response);
			break;
		}
		default:
			break;
		}
	}

	private void queryFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String rootPath = getServletContext().getInitParameter("file_download_path");
		String filePath = request.getParameter("filePath");
		String strPathType = request.getParameter("pathType");
		int    pathType = Integer.parseInt(strPathType);
		
		if (pathType == PATH_TYPE_PART) {
			filePath = filePath==null?rootPath:rootPath+filePath;
		}
		
		String path = request.getContextPath();
		String baseUrl = request.getScheme() + "://" 
		+ request.getServerName() + ":" 
				+ request.getServerPort() + path + "/";
		
		File file = new File(filePath);
		if (!file.exists()) {
			//不存在则设置错误信息，将请求转发到error.jsp
			ErrorMessage error = new ErrorMessage("文件浏览失败",
					"文件目录不存在","文件目录"+filePath+"不存在",
					baseUrl+"FileServlet?option=1&pathType=1");
			request.setAttribute("error", error);
			//转发到错误提示页面
			getServletContext().getRequestDispatcher("/WEB-INF/jsp/public/error.jsp")
			.forward(request, response);
			return;
		}
		//调用getFilesInDir方法查询目录下的所有文件，并做相应处理 
		getFilesInDir(request, response,rootPath,baseUrl, file);
		
	}

	private void getFilesInDir(HttpServletRequest request, HttpServletResponse response,
			String rootPath,String basePath, File file) throws ServletException, IOException {
		// TODO Auto-generated method stub
		File[] files = file.listFiles();
		List<MyFile> myFiles = new ArrayList<>();
		MyFile myFile = null;
		String iconUrl = "";
		for(File f:files){
			myFile = new MyFile();
			if (f.isDirectory()) {
				iconUrl = fileIconMap.get(FILE_ICON_DIR);
				myFile.setIconUrl(iconUrl);
				myFile.setImageType(false);
			}else{
				getFileIconUrl(myFile,f);
			}
			myFile.setFile(f);
			myFiles.add(myFile);
		}
		//file.getAbsolutePath()
		request.setAttribute("myFiles", myFiles);
		//将file父目录保存session的属性域
		HttpSession session = request.getSession();
		if (file.getAbsolutePath().equals(rootPath.substring(0,rootPath.lastIndexOf("\\")))) {
			session.setAttribute("parentPath", rootPath);
		}else{
			session.setAttribute("parentPath", file.getParent());
		}
		//将当前目录保存到session
		session.setAttribute("currentPath", file.getAbsolutePath());
		//将请求转发到
		getServletContext().getRequestDispatcher("/WEB-INF/jsp/files/detail.jsp")
		.forward(request, response);
	}

	private void getFileIconUrl(MyFile myFile, File f) {
		// TODO Auto-generated method stub
		String fileName = f.getName();
		int pos = fileName.lastIndexOf(".");
		String suffix = fileName.substring(pos + 1);
		
		if (strImgSuffix.indexOf(suffix)!=-1) {
			myFile.setImageType(true);
			return;
		}
		String iconUlr = fileIconMap.get(suffix);
		if (iconUlr == null) {
			myFile.setIconUrl(fileIconMap.get(FILE_ICON_DEFAULT));
		}
		myFile.setIconUrl(iconUlr);
	}

	private void addDir(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		
	}

	private void deleteFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		String rootPaht = getServletContext().getInitParameter("file_download_path");
		String filePath = request.getParameter("filePath");
		String strPathType = request.getParameter("pathType");
		int    pathType = Integer.parseInt(strPathType);
		if (pathType == PATH_TYPE_PART) {
			filePath = rootPaht + filePath;
		}
		File file = new File(filePath);
		File parentFile =  file.getParentFile();
		
		if (file.isFile()) {
			file.delete();
		}else{
			deleteDir(file);
		}
		
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" 
		+ request.getServerName() + ":" 
				+ request.getServerPort() + path + "/";
		
		getFilesInDir(request, response,rootPaht,basePath, parentFile);
	}

	private void deleteDir(File file) {
		// TODO Auto-generated method stub
		File[] files = file.listFiles();
		for(File f: files){
			if (f.isFile()) {
				f.delete();
				continue;
			}
			deleteDir(f);
		}
		file.delete();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
